package ex05.pyrmont.valves;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.Contained;
import org.apache.catalina.Container;
import org.apache.catalina.Valve;
import org.apache.catalina.comet.CometEvent;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;


public class HeaderLoggerValve implements Valve, Contained {
	protected Container container;
	
	@Override
	public Container getContainer() {
		return container;
	}

	@Override
	public void setContainer(Container container) {
		this.container = container;
	}

	@Override
	public void backgroundProcess() {

	}

	@Override
	public void event(Request request, Response response, CometEvent arg2)
			throws IOException, ServletException {

	}

	@Override
	public String getInfo() {
		return null;
	}

	@Override
	public Valve getNext() {
		return null;
	}

	@Override
	public void invoke(Request request, Response response) throws IOException,
			ServletException {
		System.out.println("Header Logger Valve");
		ServletRequest req = request.getRequest();
		if (req instanceof HttpServletRequest) {
			HttpServletRequest hreq = (HttpServletRequest) req;
			Enumeration<String> headerNames = hreq.getHeaderNames();
			while (headerNames.hasMoreElements()) {
				String headerName = headerNames.nextElement().toString();
				String headerValue = hreq.getHeader(headerName);
				System.out.println(headerName + ": " + headerValue);
			}
		}else {
			System.out.println("Not an Http Request");
		}
		System.out.println("----------------------------------------------");
	}

	@Override
	public boolean isAsyncSupported() {
		return false;
	}

	@Override
	public void setNext(Valve arg0) {

	}

}
